/**
 * 
 */
package cn.edu.nju.ws.sview.wyge.relations.adataset.relations.datasetRelations;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashSet;

import cn.edu.nju.ws.sview.cache.URIIDCache;
import cn.edu.nju.ws.sview.database.DBConnectionFactory;

/**
 * @author Weiyi Ge (geweiyi@gmail.com)
 * 2012-8-10
 *
 */
public class RelationConstants {

	/**
	 * @param relation_id
	 * @return	sub : "1"+"u"/"b"+id
	 *			prop :  "2"+"u"+pid   **********
	 * 			obj : "3"+["u"/"b"+id]/["l"+literal]
	 */
	public static HashSet<String> getWithPrefix(int relation_id){
		HashSet<String> res = new HashSet<String>();
		try {
			Connection conn = DBConnectionFactory.getConnection();
			int typeid = 0;
			try {
				typeid = URIIDCache.getInstance().getURIID(
						"http://www.w3.org/1999/02/22-rdf-syntax-ns#type", false);
			} catch (Throwable e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			PreparedStatement selps = conn.prepareStatement("SELECT s,p,o FROM re_pattern where relation_id = ?");
			selps.setInt(1, relation_id);
			ResultSet selrs = selps.executeQuery();
			while(selrs.next()){
				String s = selrs.getString(1);
				int p = selrs.getInt(2);
				String o = selrs.getString(3);
				if(!s.startsWith("v")){
					res.add("1"+s);
				}
				if(p!=typeid){
					res.add("2"+"u"+p);//==================
				}
				if(!o.startsWith("v")){
					res.add("3"+o);
				}
			}
			selrs.close();
			selps.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
		
	}
	/**
	 * @param relation_id
	 * @return	sub : "1"+"u"/"b"+id
	 *			prop :  "2"+pid
	 * 			obj : "3"+["u"/"b"+id]/["l"+literal]
	 */
	public static HashSet<String> get(int relation_id){
		HashSet<String> res = new HashSet<String>();
		try {
			Connection conn = DBConnectionFactory.getConnection();
			int typeid = 0;
			try {
				typeid = URIIDCache.getInstance().getURIID(
						"http://www.w3.org/1999/02/22-rdf-syntax-ns#type", false);
			} catch (Throwable e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			PreparedStatement selps = conn.prepareStatement("SELECT s,p,o FROM re_pattern where relation_id = ?");
			selps.setInt(1, relation_id);
			ResultSet selrs = selps.executeQuery();
			while(selrs.next()){
				String s = selrs.getString(1);
				int p = selrs.getInt(2);
				String o = selrs.getString(3);
				if(!s.startsWith("v")){
					res.add("1"+s);
				}
				if(p!=typeid){
					res.add("2"+p);
				}
				if(!o.startsWith("v")){
					res.add("3"+o);
				}
			}
			selrs.close();
			selps.close();
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
}
